import requests
import json
import os
import time

headerss = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.36'}

def saveImg(I,res,id):
    if os.path.exists(os.getcwd()+'\\LiveImg'):
        with open('LiveImg/'+id+I,'wb') as f:
            f.write(res.content)
    else:
        os.mkdir(os.getcwd()+'\\LiveImg')
        with open('LiveImg/'+id+I,'wb') as f:
            f.write(res.content)

# print(os.getcwd())

f = open('room.txt', 'r', encoding='utf-8')
num = f.read()
f.close()
param = num.split(',')

# print(len(param))
room = []

for i in param:
    url = 'https://api.live.bilibili.com/xlive/web-room/v1/index/getRoomBaseInfo?room_ids='+i+'&req_biz=video'
    htmlOne = requests.get(url,headers=headerss).json()
    resImg = requests.get(htmlOne['data']['by_room_ids'][str(i)]['cover'])
    saveImg('Live.jpg',resImg,i)
    # url2 = 'https://tenapi.cn/bilibili/?uid='+str(htmlOne['data']['by_room_ids'][id]['uid'])

    # htmlOne2 = requests.get(url2,headers=headerss).json()

    # resImg2 = requests.get(htmlOne2['data']['avatar'])
    # saveImg('userImg.jpg',resImg2)

    # print(htmlOne)
    ress = htmlOne['data']['by_room_ids'][str(i)]
    res = {"uid":str(ress['room_id']),"title":ress['title'],"name":ress['uname'],"background":i+'Live.jpg',"live_status":ress['live_status']}
    room.append(res)
print(json.dumps(room, ensure_ascii=False))
    # time.sleep(1)

# print(json.dumps(htmlOne, ensure_ascii=False))